// 导入数据库操作模块
const db = require('../../db/index')

// 获取全部朝代信息   (不获取d_state为0的朝代)
exports.getDynasty = (req, res) => {
    const selectSql = `select * from dynasty where d_state=1`
    db.query(selectSql, (err, selectRes) => {
        if(err) return res.operationSuccess('failure', 'ERR040', '获取朝代信息失败！', [])
        return res.operationSuccess('success', '', '获取朝代信息成功！', selectRes)
    })
}

// 添加朝代信息
// 先秦 汉 魏晋 南北 隋 唐 宋 金 辽 元 明 清
exports.addDynasty = (req, res) => {
    let { d_name } = req.body
    const selectSql = `select * from dynasty where d_name='${ d_name }'`
    db.query(selectSql, (err, selectRes) => {
        if(err) return res.operationFailed(err)
        if(selectRes.length == 0 || (selectRes.length != 0 && selectRes[0].d_state == 1)) return res.operationSuccess('failure', 'ERR041', '该朝代已存在！', [])
        let insertSql = ''
        if(selectRes[0].d_state == 0) insertSql = `update dynasty set d_state=1 where d_name='${ d_name }'`
        else insertSql = `insert into dynasty(d_name, d_state) values('${ d_name}', 1)`
        db.query(insertSql, (err, insertRes) => {
            if(err) return res.operationSuccess('failure', 'ERR042', '添加朝代失败！', err)
            return res.operationSuccess('success', '', '添加朝代成功！', [])
        })
    })
}

// 根据名称删除朝代信息
exports.deleteDynastyByName = (req, res) => {
    let { d_name } = req.body
    const selectSql = `select * from dynasty where d_name='${ d_name }' and d_state=1`
    db.query(selectSql, (err, selectRes) => {
        if(err) return res.operationFailed(err)
        if(selectRes.length == 0) return res.operationSuccess('failure', 'ERR043', '该朝代不存在！', [])
        const insertSql = `update dynasty set d_state=0 where d_name='${ d_name }'`
        db.query(insertSql, (err, insertRes) => {
            if(err) return res.operationSuccess('failure', 'ERR044', '删除朝代失败！', err)
            return res.operationSuccess('success', '', '删除朝代成功！', [])
        })
    })
}

// 根据名称查找朝代信息
exports.searchDynastyByName = (req, res) => {
    let { d_name } = req.body
    const selectSql = `select * from dynasty where d_name='${ d_name }' and d_state=1`
    db.query(selectSql, (err, selectRes) => {
        if(err) return res.operationSuccess('failure', 'ERR045', '查找朝代失败！', err)
        return res.operationSuccess('success', '', '查找朝代成功！', selectRes)
    })
}

// 根据朝代id查找朝代信息
exports.searchDynastyByDid = (req, res) => {
    let { did } = req.body
    const selectSql = `select * from dynasty where did=${ did } and d_state=1`
    db.query(selectSql, (err, selectRes) => {
        if(err) return res.operationSuccess('failure', 'ERR045', '查找朝代失败！', err)
        return res.operationSuccess('success', '', '查找朝代成功！', selectRes)
    })
}

